package com.wistech.search.solr4;

import java.net.MalformedURLException;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.impl.LBHttpSolrServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@SuppressWarnings("serial")
public class ServerFactoryImpl implements ServerFactory {
	private static final Logger logger = LoggerFactory
			.getLogger(ServerFactoryImpl.class);
	private String serverUrl;
	private SolrServer solrServer;
	private boolean clouded;

	@Override
	public SolrServer getSolrServer() throws SearchException {
		return this.solrServer;
	}

	@Override
	public void destroy() throws SearchException {
		solrServer.shutdown();
	}

	public void buildServer() {
		try {
			if (clouded) {
				CloudSolrServer solrServer;
				solrServer = new CloudSolrServer(serverUrl);
				solrServer.setZkClientTimeout(100000);
				solrServer.setZkConnectTimeout(1000000);
				this.solrServer = solrServer;
			} else {
				LBHttpSolrServer solrServer = new LBHttpSolrServer(serverUrl);
				solrServer.setAliveCheckInterval(60 * 1000);
				solrServer.setConnectionTimeout(100000);
				solrServer.setSoTimeout(100000);
				this.solrServer = solrServer;
			}
		} catch (MalformedURLException e) {
			String msg = "building SolrServer error.";
			logger.error(msg, e);
			throw new SearchException(msg, e);
		}
	}

	public void setServerUrl(String serverUrl) {
		this.serverUrl = serverUrl;
	}

	public void setClouded(boolean clouded) {
		this.clouded = clouded;
	}
}
